// address-edit.js
Page({
  data: {
    addressId: null,
    isEdit: false,
    formData: {
      name: '',
      phone: '',
      province: '',
      city: '',
      district: '',
      detail: '',
      isDefault: false
    },
    regions: [], // 初始为空数组，让地区选择器显示"请选择地区"
    loading: false,
    userInfo: {
      isLogin: false
    }
  },

  onLoad(options) {
    console.log('地址编辑页面加载，参数:', options)
    this.loadUserInfo()
    
    // 检查是否是编辑模式
    if (options.id) {
      console.log('编辑模式，地址ID:', options.id)
      this.setData({
        addressId: options.id,
        isEdit: true
      })
      this.loadAddressDetail(options.id)
    } else {
      console.log('添加模式')
    }
  },

  onShow() {
    console.log('地址编辑页面显示，当前数据:', this.data)
    
    // 如果是编辑模式且还没有地区数据，尝试重新设置
    if (this.data.isEdit && this.data.addressId && (!this.data.regions || this.data.regions.length === 0)) {
      console.log('检测到编辑模式但地区数据为空，重新加载')
      this.loadAddressDetail(this.data.addressId)
    }
  },

  // 加载用户信息
  loadUserInfo() {
    const app = getApp()
    const userInfo = app.getUserInfo()
    this.setData({ userInfo })
    
    if (!userInfo.isLogin) {
      wx.showModal({
        title: '提示',
        content: '请先登录',
        success: (res) => {
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/login/login'
            })
          } else {
            wx.navigateBack()
          }
        }
      })
    }
  },

  // 加载地址详情（编辑模式）
  loadAddressDetail(addressId) {
    this.setData({ loading: true })
    
    wx.request({
      url: `http://localhost:8082/user/addresses/${addressId}`,
      method: 'GET',
      header: {
        'Authorization': 'Bearer ' + wx.getStorageSync('token')
      },
      success: (res) => {
        this.setData({ loading: false })
        console.log('API响应:', res)
        
        if (res.data && res.data.code === 200) {
          const address = res.data.data
          console.log('获取到的地址数据:', address)
          
          // 先设置基本信息
          this.setData({
            formData: {
              name: address.receiver || '',
              phone: address.phone || '',
              province: address.province || '',
              city: address.city || '',
              district: address.district || '',
              detail: address.detailAddress || '',
              isDefault: address.isDefault == 1 || address.isDefault === true
            }
          })
          
          // 单独设置地区数据，使用nextTick确保DOM更新
          wx.nextTick(() => {
            const regions = [
              address.province || '',
              address.city || '',
              address.district || ''
            ]
            console.log('准备设置地区数据:', regions)
            
            this.setData({
              regions: regions
            })
            
            console.log('地区数据设置完成，当前regions:', this.data.regions)
          })
        } else {
          console.log('API返回错误:', res.data)
          wx.showToast({
            title: res.data?.message || '获取地址详情失败',
            icon: 'none'
          })
        }
      },
      fail: (err) => {
        console.error('获取地址详情失败:', err)
        this.setData({ loading: false })
        wx.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        })
      }
    })
  },

  // 输入框变化
  onInputChange(e) {
    const field = e.currentTarget.dataset.field
    const value = e.detail.value
    
    this.setData({
      [`formData.${field}`]: value
    })
  },

  // 选择地区
  onRegionChange(e) {
    const regions = e.detail.value
    console.log('选择的地区:', regions)
    this.setData({
      regions: regions,
      'formData.province': regions[0] || '',
      'formData.city': regions[1] || '',
      'formData.district': regions[2] || ''
    })
  },

  // 切换默认地址
  onDefaultChange(e) {
    this.setData({
      'formData.isDefault': e.detail.value
    })
  },

  // 表单验证
  validateForm() {
    const { name, phone, province, city, district, detail } = this.data.formData
    
    if (!name.trim()) {
      wx.showToast({
        title: '请输入收货人姓名',
        icon: 'none'
      })
      return false
    }
    
    if (!phone.trim()) {
      wx.showToast({
        title: '请输入手机号',
        icon: 'none'
      })
      return false
    }
    
    // 简单的手机号验证
    const phoneRegex = /^1[3-9]\d{9}$/
    if (!phoneRegex.test(phone)) {
      wx.showToast({
        title: '请输入正确的手机号',
        icon: 'none'
      })
      return false
    }
    
    if (province === '请选择' || !province) {
      wx.showToast({
        title: '请选择省份',
        icon: 'none'
      })
      return false
    }
    
    if (city === '请选择' || !city) {
      wx.showToast({
        title: '请选择城市',
        icon: 'none'
      })
      return false
    }
    
    if (district === '请选择' || !district) {
      wx.showToast({
        title: '请选择区县',
        icon: 'none'
      })
      return false
    }
    
    if (!detail.trim()) {
      wx.showToast({
        title: '请输入详细地址',
        icon: 'none'
      })
      return false
    }
    
    return true
  },

  // 保存地址
  onSave() {
    if (!this.validateForm()) {
      return
    }
    
    this.setData({ loading: true })
    
    const url = this.data.isEdit 
      ? `http://localhost:8082/user/addresses/update`
      : `http://localhost:8082/user/addresses/add`
    
    const method = this.data.isEdit ? 'PUT' : 'POST'
    
    const data = {
      receiver: this.data.formData.name,
      phone: this.data.formData.phone,
      province: this.data.formData.province,
      city: this.data.formData.city,
      district: this.data.formData.district,
      detailAddress: this.data.formData.detail,
      isDefault: this.data.formData.isDefault ? 1 : 0
    }
    
    // 编辑模式需要传递ID
    if (this.data.isEdit) {
      data.id = this.data.addressId
    }
    
    wx.request({
      url: url,
      method: method,
      header: {
        'Authorization': 'Bearer ' + wx.getStorageSync('token'),
        'Content-Type': 'application/json'
      },
      data: data,
      success: (res) => {
        this.setData({ loading: false })
        
        if (res.data && res.data.code === 200) {
          wx.showToast({
            title: this.data.isEdit ? '修改成功' : '添加成功',
            icon: 'success'
          })
          
          // 延迟返回，让用户看到成功提示
          setTimeout(() => {
            wx.navigateBack()
          }, 1500)
        } else {
          wx.showToast({
            title: res.data?.message || (this.data.isEdit ? '修改失败' : '添加失败'),
            icon: 'none'
          })
        }
      },
      fail: (err) => {
        console.error('保存地址失败:', err)
        this.setData({ loading: false })
        wx.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        })
      }
    })
  },

  // 返回
  onBack() {
    wx.navigateBack()
  },

  // 去登录
  goToLogin() {
    wx.navigateTo({
      url: '/pages/login/login'
    })
  }
})
